package com.cy.oa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cy.oa.entity.LeaveBean;
import com.cy.oa.service.LeaveService;
import com.cy.system.annotation.DataSource;
import com.cy.system.config.DataSourceContextHolder;
import com.cy.system.entity.User;

@Controller
@RequestMapping("/apply")
public class ApplyController {
	@Resource
	LeaveService leaveService;
	@Resource
	TaskService taskService;

	@RequestMapping("/index")
	public String apply() {
		return "oa/apply/index";
	}
	
	@RequestMapping(value="/applyLeave",method=RequestMethod.POST)
	/*@DataSource(dataSourceType="activitiDataSource")*/  //这样切换数据源无效，因为Service中加了事务
	public String appleLeave(LeaveBean leaveBean,String outcome,Model model) {             //加@RequestBody,http:415错误
		DataSourceContextHolder.setDbType("activitiDataSource");
		boolean res = leaveService.applyLeave(leaveBean,outcome);
		DataSourceContextHolder.clearDbType();
		if(res) {
			model.addAttribute("msg", "申请成功！");
		}else {
			model.addAttribute("msg", "申请失败！");
		}
		return "oa/apply/index";
	}
	
	@RequestMapping("/handleIndex")
	public String handleApply() {
		return "oa/apply/handleIndex";
	}
	
	@RequestMapping("/leaveTaskList")
	public String leaveTaskList() {
		
		return "oa/apply/leaveTaskListPage";
	}
	
	@RequestMapping("/leaveTaskListRe")
	@ResponseBody
	public List<Map<String,Object>> leaveTaskListRe(HttpSession session){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		User user = (User)session.getAttribute("userSession");
		List<Task> taskList = taskService.createTaskQuery().taskAssignee(Integer.toString(user.getUserId()))
		             .orderByTaskCreateTime().desc().list();
		for(Task task : taskList) {
			HashMap<String,Object> taskMap = new HashMap<String,Object>();
			taskMap.put("id", task.getId());
			taskMap.put("name", task.getName());
			taskMap.put("assignee", user.getUserName());
			taskMap.put("createTime", sdf.format(task.getCreateTime()));
			taskMap.put("processInstanceId", task.getProcessInstanceId());	
			taskMap.put("formKey", task.getFormKey());		
			list.add(taskMap);
		}
		return list;
	}
	
	
}
